#import "LZCustomTabBar.h"

@implementation LZCustomTabBar

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupCenterButton];
    }
    return self;
}

- (void)setupCenterButton {
    _centerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_centerButton setImage:[UIImage imageNamed:@"tab_center"] forState:UIControlStateNormal];
    [_centerButton addTarget:self action:@selector(centerButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_centerButton];
}

- (void)centerButtonClick {
    if ([self.customDelegate respondsToSelector:@selector(centerButtonDidClick)]) {
        [self.customDelegate centerButtonDidClick];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];

    // 重新布局中间按钮
    CGFloat buttonW = self.frame.size.width / 5;
    CGFloat buttonH = self.frame.size.height;
    CGFloat buttonY = 0;

    _centerButton.frame = CGRectMake((self.frame.size.width - buttonW) / 2, buttonY, buttonW, buttonH);

    // 重新布局其他tabBarButton
    NSInteger index = 0;
    for (UIView *tabBarButton in self.subviews) {
        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            CGFloat buttonX = index * buttonW;
            if (index >= 2) { // 中间按钮后的位置
                buttonX += buttonW;
            }
            tabBarButton.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
            index++;
        }
    }
}

@end
